package com.dnake.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.dnake.Constant;
import com.dnake.entity.BaseHttpBean;
import com.dnake.entity.EventBusUpdateBean;
import com.dnake.entity.VersionBean;
import com.dnake.misc.SysAccess;
import com.dnake.panel.BuildConfig;
import com.dnake.utils.ToastUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

import static com.hyphenate.chat.EMGCMListenerService.TAG;

public class UpdateAppService extends Service {
    public static Context mContext = null;
    public UpdateAppService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        EventBus.getDefault().register(this);
    }
    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 更新app
     *
     * @param eventBusUpdateBean
     */
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEventUpdate(EventBusUpdateBean eventBusUpdateBean) {
        getVersion();
    }

    /**
     * 检测APP版本
     */
    private void getVersion() {
        RequestParams params = new RequestParams(Constant.HTTP_URL + "/community/device/app/version/3");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Logger.json(result);
                if (!TextUtils.isEmpty(result)) {
                    BaseHttpBean httpBean = JSON.parseObject(result, BaseHttpBean.class);
                    if (!TextUtils.isEmpty(httpBean.getData())) {
                        VersionBean versionBean = JSON.parseObject(httpBean.getData(),VersionBean.class);
                        if (versionBean.getLatestCode()> BuildConfig.VERSION_CODE){
                            ToastUtil.showSuccessView("有新版本更新");
                            downloadApp(versionBean.getAddress());
                        }else {
                            ToastUtil.showSuccessView("已是最新版本");
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    /**
     * 下载
     */
    private void downloadApp(String url) {
        RequestParams params = new RequestParams(url);
        params.setAutoResume(true);//断点下载
        params.setAutoRename(false);
        params.setSaveFilePath("/storage/sdcard0/Download/app_weker.apk");
        Log.e(TAG, "downloadApp: APP升级");
        x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(File result) {
                Log.e(TAG, "onSuccess: 下载成功");
                updateApp();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "onError: " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                ToastUtil.show("正在更新，请稍后  进度："+current*100/total+"%");
            }
        });

    }
    /**
     * 升级
     */
    private void updateApp() {
        SysAccess.upgrade("/storage/sdcard0/Download/app_weker.apk","app_weker",0);

//        try {
//            Class<?> clazz = Class.forName("android.os.ServiceManager");
//            Method method_getService = clazz.getMethod("getService", String.class);
//            IBinder bind = (IBinder) method_getService.invoke(null, "package");
//
//            IPackageManager iPm = IPackageManager.Stub.asInterface(bind);
//            iPm.installPackage(Uri.fromFile(apkFile), null, 2, apkFile.getName());
//        } catch (Exception e) {
//            ToastUtil.showFailView("安装失败");
//            e.printStackTrace();
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }
}
